from pyxmpp2.streamevents import DisconnectedEvent
from pyxmpp2.message import Message 
from pyxmpp2.jid import JID
import logging
from pyxmpp2.interfaces import EventHandler, event_handler, QUIT
from pyxmpp2.streamevents import AuthorizedEvent
from pyxmpp2.client import Client
from pyxmpp2.interfaces import presence_stanza_handler, message_stanza_handler
from xml.etree.ElementTree import tostring
from pyxmpp2.interfaces import XMPPFeatureHandler

logging.getLogger().setLevel(logging.INFO)

my_jid=JID('id0438c980b8e5ef0d77e8025b0880a696@localhost')
password='sharebf373c5a0e5dd7e9c9acd0cb4613179f'
jid_to = 'idb9a8ad72f1344a3ea1a111f2015dc8d2@localhost'
my_message='hello 5222'

from pyxmpp2.settings import XMPPSettings
settings = XMPPSettings({ "password": password,'port':5222,'server':'127.0.0.1' })

class MyHandler(EventHandler,XMPPFeatureHandler):
    @event_handler()
    def handle_any_event(self, event):
        logging.info(u"-- {0}".format(event))
        
    @message_stanza_handler()
    def handle_message(self, stanza):
        logging.info(u"RECV: {0}".format(tostring(stanza.get_xml())))
        try:
            stanza.body.index('i will go')
            print('\nGO\n')
            return None
        except:
            pass
        msg = Message( stanza_type = stanza.stanza_type,
                from_jid = stanza.to_jid, to_jid = stanza.from_jid,
                subject = 'Re: %s'%stanza.subject, body = stanza.body,
                thread = stanza.thread )
        return msg
        
    @event_handler(DisconnectedEvent)
    def handle_disconnected(self, event):
        return QUIT

from _thread import start_new_thread
import time
from xml.etree.ElementTree import tostring
def send_proc( handler1 ):
    message = Message(to_jid = jid_to,body = my_message)
    global client
    for i in range(5):
        c=input('enter...')
        client.send(message)
        logging.info(u"SEND: {0}".format(tostring(message.get_xml())))
    client.disconnect()
    
h1 = MyHandler()
client = Client(my_jid, [ h1 ], settings)
client.connect()
start_new_thread( send_proc,(h1,) )
try:
    client.run()
except:
    client.disconnect()
